package com.demo.study.algorithm.leetcode.array.easy;

import org.junit.Test;

/**
 * LT35
 * <a href="https://leetcode.cn/problems/search-insert-position">搜索插入位置</a>
 *
 * @author Baymax
 * @since 2024-11-17
 */
public class LT35 {

    @Test
    public void run() {
        int num = searchInsert1(new int[]{1, 3, 5, 6}, 2);
        System.out.println(num);
    }

    /*
    0,1,2  (0+2)/2=1
    0,1,2,3 (0+3)/2=1
    0,1,2,3,4,5 (0+5)/2=2
     */
    public int searchInsert(int[] nums, int target) {
        if (nums[0] > target) {
            return 0;
        }
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] >= target) {
                return i;
            }
        }
        return nums.length;
    }

    // 下面这个是错的
    public int searchInsert1(int[] nums, int target) {
        if (nums[0] > target) {
            return 0;
        }
        if (nums[nums.length - 1] < target) {
            return nums.length;
        }
        int i = 0;
        int j = nums.length - 1;
        while (i < j) {
            if (nums[i] == target) {
                return i;
            } else if (nums[j] == target) {
                return j;
            } else {
                i++;
                j--;
            }
        }
        return i - 1;
    }

    // 正解1
    public int searchInsert2(int[] nums, int target) {
        int n = nums.length;
        int left = 0, right = n - 1, ans = n;
        while (left <= right) {
            int mid = ((right - left) >> 1) + left;

            if (target == nums[mid]) {
                return mid;
            } else if (target < nums[mid]) {
                ans = mid;
                right = mid - 1;
            } else {
                left = mid + 1;
            }
        }
        return ans;
    }

    // 正解2
    public int searchInsert3(int[] nums, int target) {
        int left = 0, right = nums.length - 1;
        while (left <= right) {
            int mid = (left + right) / 2;
            if (nums[mid] < target) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        return left;
    }
}
